﻿#region License, Terms and Conditions
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */
#endregion
using System;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using pesta.Auth;
using Pesta.Engine.auth;
using raya.Library;
using raya.Models.applications;

namespace raya.Controllers
{
    //[HandleError]
    public class prefsController : baseController
    {
        [ValidateInput(false)]
        public void Set()
        {
            if (String.IsNullOrEmpty(Request.QueryString["st"]) ||
                String.IsNullOrEmpty(Request.QueryString["name"]) ||
                String.IsNullOrEmpty(Request.QueryString["value"]))
            {
                Response.StatusCode = (int) HttpStatusCode.BadRequest;
                Response.StatusDescription = "<html><body><h1>400 - Bad Request</h1></body></html>";
		    } 
            else 
            {
			    try 
                {
				    String st = HttpUtility.UrlDecode(Request.QueryString["st"]);
				    String key = HttpUtility.UrlDecode(Request.QueryString["name"]);
				    String value = HttpUtility.UrlDecode(Request.QueryString["value"]);
                    st = Encoding.UTF8.GetString(Convert.FromBase64String(HttpUtility.UrlDecode(st)));
				    var token = BasicSecurityToken.createFromToken(st, int.Parse(RayaSettings.St_max_age));
				    var appId = token.getAppId();
				    var viewer = token.getViewerId();
				    var apps = new applications();
#if AZURE
                    apps.set_application_pref(viewer, appId, key, value);
#else
                    apps.set_application_pref(int.Parse(viewer), int.Parse(appId), key, value);
#endif

                }
                catch (Exception ex) 
                {
                    Response.StatusCode = (int) HttpStatusCode.BadRequest;
                    Response.StatusDescription = "<html><body><h1>400 - Bad Request</h1>" + ex.Message + "</body></html>";
			    }
		    }
        }
    }
}
